package com.newshub.ai.controller;

import com.newshub.ai.model.dto.BiQueryRequest;
import com.newshub.ai.service.ChatBIService;
import com.newshub.ai.service.ChatBISessionService;
import com.newshub.ai.util.QuestionAnalyzer;
import com.newshub.ai.util.QuestionType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;

/**
 * ChatBI 控制器 - 流式版本
 */
@Slf4j
@RestController
@RequestMapping("/api/ai/bi")
@CrossOrigin(origins = "*")
public class ChatBIController {
    
    @Autowired
    private ChatBIService chatBIService;
    
    @Autowired
    private ChatBISessionService sessionService;
    
    @Autowired
    private QuestionAnalyzer questionAnalyzer;
    
    /**
     * 流式 BI 查询接口
     */
    @PostMapping("/query-stream")
    public SseEmitter queryStream(@RequestBody BiQueryRequest request) {
        log.info("收到流式 BI 查询请求: {}", request.getQuery());
        return chatBIService.processQueryStream(request);
    }
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        try {
            Map<String, Object> status = chatBIService.getHealthStatus();
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            log.error("健康检查失败: {}", e.getMessage());
            return ResponseEntity.status(500).body(
                Map.of("overall", "error", "error", e.getMessage())
            );
        }
    }
    
    /**
     * 获取支持的图表类型
     */
    @GetMapping("/chart-types")
    public ResponseEntity<Map<String, Object>> getChartTypes() {
        Map<String, Object> chartTypes = Map.of(
            "types", new String[]{"bar", "line", "pie", "table"},
            "descriptions", Map.of(
                "bar", "柱状图 - 适合分类数据对比",
                "line", "折线图 - 适合时间趋势分析",
                "pie", "饼图 - 适合占比分析",
                "table", "表格 - 适合详细数据展示"
            )
        );
        
        return ResponseEntity.ok(chartTypes);
    }
    
    /**
     * 获取支持的时间范围
     */
    @GetMapping("/time-ranges")
    public ResponseEntity<Map<String, Object>> getTimeRanges() {
        Map<String, Object> timeRanges = Map.of(
            "ranges", new String[]{"today", "yesterday", "week", "month", "year"},
            "descriptions", Map.of(
                "today", "今天",
                "yesterday", "昨天",
                "week", "最近7天",
                "month", "最近30天",
                "year", "最近一年"
            )
        );
        
        return ResponseEntity.ok(timeRanges);
    }
    
    /**
     * 测试接口
     */
    @GetMapping("/test")
    public ResponseEntity<Map<String, Object>> test() {
        return ResponseEntity.ok(Map.of(
            "message", "ChatBI 服务运行正常",
            "timestamp", System.currentTimeMillis(),
            "version", "1.0.0"
        ));
    }
    
    /**
     * 清空指定会话
     */
    @DeleteMapping("/session/{sessionId}")
    public ResponseEntity<Map<String, Object>> clearSession(@PathVariable String sessionId) {
        try {
            sessionService.clearSession(sessionId);
            return ResponseEntity.ok(Map.of(
                "message", "会话已清空",
                "sessionId", sessionId,
                "timestamp", System.currentTimeMillis()
            ));
        } catch (Exception e) {
            log.error("清空会话失败: {}", e.getMessage());
            return ResponseEntity.status(500).body(Map.of(
                "error", "清空会话失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取会话统计信息
     */
    @GetMapping("/session/stats")
    public ResponseEntity<Map<String, Object>> getSessionStats() {
        try {
            Map<String, Object> stats = sessionService.getSessionStats();
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("获取会话统计失败: {}", e.getMessage());
            return ResponseEntity.status(500).body(Map.of(
                "error", "获取会话统计失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 检查会话是否存在
     */
    @GetMapping("/session/{sessionId}/exists")
    public ResponseEntity<Map<String, Object>> checkSessionExists(@PathVariable String sessionId) {
        try {
            boolean exists = sessionService.hasSession(sessionId);
            return ResponseEntity.ok(Map.of(
                "sessionId", sessionId,
                "exists", exists,
                "timestamp", System.currentTimeMillis()
            ));
        } catch (Exception e) {
            log.error("检查会话失败: {}", e.getMessage());
            return ResponseEntity.status(500).body(Map.of(
                "error", "检查会话失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 分析问题类型
     */
    @PostMapping("/analyze")
    public ResponseEntity<Map<String, Object>> analyzeQuestion(@RequestBody Map<String, String> request) {
        try {
            String query = request.get("query");
            if (query == null || query.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "error", "查询内容不能为空"
                ));
            }
            
            QuestionAnalyzer.QuestionAnalysisResult result = questionAnalyzer.analyzeQuestion(query);
            
            return ResponseEntity.ok(Map.of(
                "question", result.getQuestion(),
                "questionType", result.getQuestionType().getDisplayName(),
                "needsChart", result.isNeedsChart(),
                "recommendedChartType", result.getRecommendedChartType(),
                "analysis", result.getAnalysis(),
                "timestamp", System.currentTimeMillis()
            ));
            
        } catch (Exception e) {
            log.error("问题分析失败: {}", e.getMessage());
            return ResponseEntity.status(500).body(Map.of(
                "error", "问题分析失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 获取支持的问题类型
     */
    @GetMapping("/question-types")
    public ResponseEntity<Map<String, Object>> getQuestionTypes() {
        try {
            Map<String, Object> types = Map.of(
                "types", QuestionType.values(),
                "descriptions", Map.of(
                    "COMPARISON", "对比类问题：适合柱状图展示",
                    "DISTRIBUTION", "分布类问题：适合饼图展示", 
                    "TREND", "趋势类问题：适合折线图展示",
                    "DETAIL", "详情类问题：不需要图表展示",
                    "ANALYSIS", "分析类问题：可能不需要图表展示",
                    "UNKNOWN", "未知类型：默认不生成图表"
                )
            );
            
            return ResponseEntity.ok(types);
            
        } catch (Exception e) {
            log.error("获取问题类型失败: {}", e.getMessage());
            return ResponseEntity.status(500).body(Map.of(
                "error", "获取问题类型失败: " + e.getMessage()
            ));
        }
    }
}
